/**
 *  build前端项目并git提交，移动前端打包后文件到后端工程中，并git提交
 *  	使用：
 *  		node build.js 
 *  		node build.js nobuild  此时跳过gulp build和提交前端工程这一步
 *  	配置：
 *      修改下面的文件路径变量：targetRootDir和srcRootDir
 *      npm install sync-exec
 *      npm install wrench
 */

var sync_exec = require('sync-exec');
var exec = function(command, options) {
	console.log("\x1b[1m exec in dir \x1b[32m", options && options.cwd, "\x1b[0m with command:\x1b[32m", command, "\x1b[0m");
	var result = sync_exec.apply(null, arguments);
	console.log(result);
	if (result.stderr !== '') {
		console.error('\x1b[31m something wrong,exit\x1b[0m');
		process.exit(1);
	} else {
		return result;
	}
}
var wrench = require('wrench');
var path = require('path');

var targetRootDir = 'E:/project/operation/';
var srcRootDir = 'E:/project/VCOP/';

var targetDir = path.join(targetRootDir, 'manage-web/src/main/webapp/WEB-INF');
var srcDir = path.join(srcRootDir, '/build');


var arguments = process.argv.splice(2);
if (!arguments[0] || arguments[0] != 'nobuild') {
	var result = exec('git pull', {
		cwd: srcRootDir
	});

	console.log("start build front project, this may take some minutes , just be patient...");
	var result = exec('gulp build --target develop', {
		cwd: srcRootDir
	});
	if (result.status !== 0) return console.error('build front project with error, exit');

	var result = exec('git add .', {
		cwd: srcRootDir
	});
	var result = exec('git commit -m "build"', {
		cwd: srcRootDir
	});
	var result = exec('git push origin develop', {
		cwd: srcRootDir
	});

}

console.log("move builded file to publish project");
var branchArr = ["dev"];
branchArr.forEach(function(branch) {
	exec('git checkout '+branch+' -f', {
		cwd: targetRootDir
	});
	exec('git pull', {
		cwd: targetRootDir
	});
	wrench.copyDirSyncRecursive(path.join(srcDir, '/static'), path.join(targetDir, '/static'), {
		forceDelete: true
	});
	wrench.copyDirSyncRecursive(path.join(srcDir, '/app/web/style'), path.join(targetDir, '/style'), {
		forceDelete: true
	});
	var arr = ["common", "elements", "layout", "views"];
	arr.forEach(function(name) {
		wrench.copyDirSyncRecursive(path.join(srcDir, '/app/web/WEB-INF', name), path.join(targetDir, name), {
			forceDelete: true
		});
	});

	var result = exec('git add .', {
		cwd: targetRootDir
	});

	var result = exec('git commit -m "front code commit "', {
		cwd: targetRootDir
	});

	var result = exec('git push origin '+branch, {
		cwd: targetRootDir
	});
});

/*var result = exec('git checkout develop -f',{cwd: targetRootDir});
var result = exec('git pull',{cwd: targetRootDir});
var result = exec('git merge master',{cwd: targetRootDir});
var result = exec('git push origin develop',{cwd: targetRootDir});*/

console.log("\n\n\n\x1b[32m success! \x1b[0m");